package com.atguigu.tingshu.user.context;

import com.atguigu.tingshu.user.strategy.UpdateUserPaidRecordStrategy;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class UpdateUserPaidRecordStrategyContext implements ApplicationContextAware {

    private static final Map<String , UpdateUserPaidRecordStrategy> UPDATE_USER_PAID_RECORD_STRATEGY_MAP = new ConcurrentHashMap<>() ;

    public static final UpdateUserPaidRecordStrategy getByItemType(String itemType) {
        return UPDATE_USER_PAID_RECORD_STRATEGY_MAP.get(itemType) ;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        applicationContext.getBeansOfType(UpdateUserPaidRecordStrategy.class).values()
                .forEach(updateUserPaidRecordStrategy -> {
                    String itemType = updateUserPaidRecordStrategy.getItemType();
                    UPDATE_USER_PAID_RECORD_STRATEGY_MAP.put(itemType , updateUserPaidRecordStrategy) ;
                });
    }
}
